package com.alex.controller;

import cn.hutool.core.io.FileUtil;
import com.alex.dto.FileMetaData;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;

@RestController
@RequestMapping("/file")
public class FileController {
    /**
     * 单文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) return "文件为空";

        String originalFilename = file.getOriginalFilename(); // aaa.png
        String extName = originalFilename.substring(originalFilename.lastIndexOf(".")); // .png

        String fileStoreName = System.currentTimeMillis() + extName; //17342342342.png
        String fileStorePath = "E:\\Home\\ServerFileManage\\demoUpload\\";
        File storeFile = new File(fileStorePath + fileStoreName);

        if (!storeFile.getParentFile().exists()) {
            storeFile.getParentFile().mkdirs();
        }

        try {
            file.transferTo(storeFile);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return fileStorePath + fileStoreName;
    }

    /**
     * 单文件下载 预览
     *
     * @param fileName
     * @param response
     * @throws IOException
     */
    @GetMapping("/download/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse response) throws IOException {
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));  // 附件下载
        //response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(fileName, "UTF-8"));  // 预览

        String fileStorePath = "E:\\Home\\ServerFileManage\\demoUpload\\";

        String filePath = fileStorePath + File.separator + fileName;
        if (!cn.hutool.core.io.FileUtil.exist(filePath)) {
            return;
        }
        try {
            byte[] bytes = FileUtil.readBytes(filePath);
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(bytes);  // 数组是一个字节数组，也就是文件的字节流数组
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 多文件上传
     *
     * @param multipartFileMap
     */
    @PostMapping("/upload3")
    public void post5(@RequestParam Map<String, MultipartFile> multipartFileMap) {
        multipartFileMap.forEach((name, file) -> {
            System.out.println(name);
            System.out.println(file.getOriginalFilename());
        });
    }

    /**
     * 文件上传 附加 meta-data 属性(JSON)
     *
     * @param multipartFile
     * @param fileMetaData
     */
    @PostMapping("upload4")
    public void upload3(@RequestPart("file") MultipartFile multipartFile, @RequestPart("meta-data") FileMetaData fileMetaData) {
        System.out.println("filename=" + multipartFile.getOriginalFilename());
        System.out.println(fileMetaData.toString());
    }

}

